package com.alibaba.citrus.cr.platform.enhance.repository.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import javax.annotation.Resource;

import com.alibaba.citrus.cr.common.annotation.RepositoryInvoker;
import com.alibaba.citrus.cr.platform.enhance.repository.DimensionWriteRepository;
import com.alibaba.citrus.cr.sales.plan.api.setting.SalesPlanScItemQueryService;
import com.alibaba.lattice2.epoch.sdk.model.Result;

import com.epoch.app.bcorder.model.dto.QueryWarehouseByIdRequest;
import com.epoch.app.bcorder.model.dto.SearchReqDTO;
import com.epoch.app.bcorder.model.dto.SearchScItemRequest;
import com.epoch.app.bcorder.model.dto.WarehouseInfo;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.bcorder.service.UnifiedInventoryService;
import com.epoch.app.crplatformenhance.api.organizationquery.service.OrganizationQueryService;
import com.epoch.app.crplatformenhance.dimension.dto.CreateDimensionResponse;
import com.epoch.app.crplatformenhance.dimension.dto.DeleteDimensionRequest;
import com.epoch.app.crplatformenhance.dimension.dto.UpdateByPriorityRequest;
import com.epoch.app.crplatformenhance.dimension.dto.UpdateDimensionResponse;
import com.epoch.app.crplatformenhance.dimension.model.Dimension;
import com.epoch.app.crplatformenhance.dimension.service.DimensionService;
import com.epoch.app.crplatformenhance.dto.request.IdQueryRequest;
import com.epoch.app.crplatformenhance.enums.DimensionTypeEnum;
import com.epoch.app.crplatformenhance.sdo.DimensionSDO;
import com.epoch.app.crplatformenhance.sdo.OrganizationSDO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

@Component
public class DimensionWriteRepositoryImpl implements DimensionWriteRepository {

    @Resource
    private DimensionService dimensionService;

    @Resource
    private OrganizationQueryService organizationQueryService;

    @Resource
    private SalesPlanScItemQueryService salesPlanScItemQueryService;

    @Resource
    private BaseDataService baseDataService;
    @Resource
    private UnifiedInventoryService unifiedInventoryService;

    @Override
    @RepositoryInvoker
    public String update(DimensionSDO dimensionSDO) {
        DeleteDimensionRequest dimensionRequest = new DeleteDimensionRequest();
        if (null != dimensionSDO.getId()) {
            dimensionRequest.setId(dimensionSDO.getId());
        }
        Dimension dimension = dimensionConverter(dimensionSDO);
        dimension.setId(dimensionSDO.getId());
        UpdateDimensionResponse updateDimensionResponse = dimensionService.updateDimension(dimension);
        if (updateDimensionResponse.getCount() != 1) {
            throw new RuntimeException("修改维度表失败");
        }
        return String.valueOf(dimensionSDO.getId());
    }

    @Override
    @RepositoryInvoker
    public String create(DimensionSDO dimensionSDO) {
        Dimension dimension = dimensionConverter(dimensionSDO);
        CreateDimensionResponse dimension1 = dimensionService.createDimension(dimension);
        return dimension1.getLastInsertId();
    }

    @Override
    public Boolean modify(DimensionSDO dimensionSDO) {
        Dimension dimension = dimensionConverter(dimensionSDO);
        dimension.setId(dimensionSDO.getId());
        dimensionService.updateDimension(dimension);
        return true;
    }


    @Override
    public String delete(DimensionSDO dimensionSDO) {
        DeleteDimensionRequest request = new DeleteDimensionRequest();
        request.setId(dimensionSDO.getId());
        dimensionService.deleteDimension(request);
        return dimensionSDO.getId().toString();
    }

    @Override
    public void deleteByPriority(DimensionSDO dimensionSDO) {
        DeleteDimensionRequest request = new DeleteDimensionRequest();
        request.setId(dimensionSDO.getId());
        dimensionService.deleteDimension(request);

        UpdateByPriorityRequest updateRequest = new UpdateByPriorityRequest();
        updateRequest.setCode(dimensionSDO.getCode());
        updateRequest.setPriority(dimensionSDO.getPriority());
        updateRequest.setStrategyId(dimensionSDO.getStrategyId());
        dimensionService.updateByPriority(updateRequest);
    }

    private Dimension dimensionConverter(DimensionSDO dimensionSDO) {
        Dimension dimension = new Dimension();
        dimension.setCode(dimensionSDO.getCode());
        dimension.setCodeName(dimensionSDO.getCodeName());
        dimension.setValue(dimensionSDO.getValue());
        dimension.setRuleName(dimensionSDO.getRuleName());
        dimension.setRuleValue(dimensionSDO.getRuleValue());
        dimension.setStatus(dimensionSDO.getStatus());
        dimension.setValidBeginTime(dimensionSDO.getValidBeginTime());
        dimension.setValidEndTime(dimensionSDO.getValidEndTime());
        dimension.setExecuteAction(dimensionSDO.getExecuteAction());
        dimension.setStrategyId(dimensionSDO.getStrategyId());
        dimension.setDetails(dimensionSDO.getDetails());
        dimension.setCreator(dimensionSDO.getCreator());
        dimension.setGmt_create(dimensionSDO.getGmtCreate());
        dimension.setUpdater(dimensionSDO.getUpdater());
        dimension.setValueName(dimensionSDO.getValueName());
        dimension.setPriority(dimensionSDO.getPriority());
        dimension.setOutCode(getDimensionOutCode(dimensionSDO));
        return dimension;
    }

    public String getDimensionOutCode(DimensionSDO request) {
        // 部门、组织
        if (StringUtils.equals(DimensionTypeEnum.DEPARTMENT.getCode(), request.getCode()) ||
                StringUtils.equals(DimensionTypeEnum.ORGANIZE.getCode(), request.getCode())) {
            IdQueryRequest idQueryRequest = new IdQueryRequest();
            idQueryRequest.setId(request.getValue());
            Result<OrganizationSDO> detail = organizationQueryService.getOrganizationDetail(idQueryRequest);
            if (Objects.isNull(detail) || Objects.isNull(detail.getResult())) {
                return null;
            }
            return detail.getResult().getOutCode();
        }
        // 渠道
        if (StringUtils.equals(DimensionTypeEnum.CHANNEL.getCode(), request.getCode()) ||
                StringUtils.equals(DimensionTypeEnum.SALESMAN.getCode(), request.getCode())) {
            return request.getValue();
        }

        // 渠道
        if (StringUtils.equals(DimensionTypeEnum.STORE_ROOM.getCode(), request.getCode())) {

            QueryWarehouseByIdRequest idRequest = new QueryWarehouseByIdRequest();
            idRequest.setId(request.getValue());
            Result<WarehouseInfo> result = unifiedInventoryService.queryWarehouseById(idRequest);
            if (Objects.isNull(result) || Objects.isNull(result.getResult())) {
                return null;
            }
            return result.getResult().getCode();
        }

        // 货品
        if (StringUtils.equals(DimensionTypeEnum.GOODS.getCode(), request.getCode())) {
            SearchScItemRequest searchScItemRequest = new SearchScItemRequest();
            SearchReqDTO searchReqDTO = new SearchReqDTO();
            List<String> list = new ArrayList<>();
            if (org.apache.commons.lang.StringUtils.isNotBlank(request.getValue())) {
                list.add(request.getValue());
                searchReqDTO.setScItemIds(list);
                searchScItemRequest.setSearchReqDTO(searchReqDTO);
                Result<List<com.epoch.app.bcorder.model.dto.ScItemSDO>> result = baseDataService.searchScItem(searchScItemRequest);
                if (CollectionUtils.isNotEmpty(result.getResult())){
                    return result.getResult().get(0).getOuterId();
                }
            }
        }
        return null;
    }


}
